﻿using Aspose.Cells;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfSnqkGasAnalysis.Common;
using WpfSnqkGasAnalysis.IData;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis.IBusiness_impl
{
    /// <summary>
    /// 水露点，业务处理
    /// </summary>
    /// 创建时间：2022-12-23 14:37:14。作者：王浩力
    public class WaterPointBusiness : BaseBusiness
    {
        readonly IWater_point_itemDAL water_Point_ItemDAL = ServicesHelpter.GetService<IWater_point_itemDAL>();
        readonly IWater_pointDAL water_PointDAL = ServicesHelpter.GetService<IWater_pointDAL>();
        readonly IWater_check_historyDAL water_Check_HistoryDAL = ServicesHelpter.GetService<IWater_check_historyDAL>();
        readonly ISource_dictDAL source_DictDAL = ServicesHelpter.GetService<ISource_dictDAL>();

        /// <summary>
        /// 新增Water_point_item
        /// </summary>
        /// <param name="water_Point_Item"></param>
        /// <returns></returns>
        public IResult AddItem(Water_point_item water_Point_Item)
        {
            return water_Point_ItemDAL.Add(water_Point_Item);
        }

        /// <summary>
        /// 删除主表记录
        /// </summary>
        /// <param name="water_PointKEY"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-23 17:32:57。作者：王浩力
        public IResult Delete(long water_PointKEY)
        {
            var info = water_PointDAL.Get(water_PointKEY);
            if (info.StepCurrent == 4)
            {
                return new Result("审核通过的不能删除");
            }

            return water_PointDAL.Delete(water_PointKEY);
        }

        /// <summary>
        /// 删除一个子项
        /// </summary>
        /// <param name="itemId">主键</param>
        /// <returns></returns>
        /// 创建时间：2022-12-23 17:50:12。作者：王浩力
        public IResult DeleteItem(long itemId)
        {
            return water_Point_ItemDAL.Delete(itemId);
        }

        /// <summary>
        /// 主表，新增
        /// </summary>
        /// <param name="water_Point"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-23 14:57:28。作者：王浩力
        public IResult Add(Water_point water_Point)
        {
            //参数检查
            if (water_Point == null)
            {
                return new Result("无效参数");
            }
            if (string.IsNullOrWhiteSpace(water_Point.Report_no))
            {
                return new Result("报告编号不可为空");
            }
            if (string.IsNullOrWhiteSpace(water_Point.WellAndWellNo))
            {
                return new Result("井站及井号不可为空");
            }

            //添加时间：2023-1-9 00:55:33
            if (string.IsNullOrWhiteSpace(water_Point.Analytime))
            {
                return new Result("分析时间不可为空");
            }
            if (water_Point.Analyst == 0)
            {
                return new Result("分析人不可为空");
            }

            //检查报告编号是否重复
            var pageCheck = Page(water_Point, 1, 1);
            if (pageCheck.Total > 0)
            {
                return new Result("报告编号已经存在");
            }

            water_Point.InputUserId = CurrentLoginUser.Id;
            water_Point.InputUserRealName = CurrentLoginUser.User_real_name;
            water_Point.Createtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            water_Point.StepCurrent = 1;

            return water_PointDAL.Add(water_Point);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="water_Point"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-26 09:13:43。作者：王浩力
        public IResult Edit(Water_point water_Point)
        {
            var old = water_PointDAL.Get(water_Point.Id);
            water_Point.InputUserId = old.InputUserId;
            water_Point.InputUserRealName = old.InputUserRealName;

            water_Point.ProofreaderUserId = old.ProofreaderUserId;
            water_Point.Proofreader = old.Proofreader;
            water_Point.ProofreaderTime = old.ProofreaderTime;
            water_Point.Createtime = old.Createtime;
            if (old.StepCurrent == 3)
            {
                water_Point.StepCurrent = 2;
            }
            else
            {
                water_Point.StepCurrent = old.StepCurrent;
            }

            return water_PointDAL.Edit(water_Point);
        }

        /// <summary>
        /// 校对
        /// </summary>
        /// <param name="water_Point"></param>
        /// <returns></returns>
        public IResult Proofread(Water_point water_Point)
        {
            var old = water_PointDAL.Get(water_Point.Id);
            water_Point.InputUserId = old.InputUserId;
            water_Point.InputUserRealName = old.InputUserRealName;

            water_Point.ProofreaderUserId   = CurrentLoginUser.Id;
            water_Point.Proofreader = CurrentLoginUser.User_real_name;
            water_Point.ProofreaderTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            water_Point.Createtime = old.Createtime;
            water_Point.StepCurrent = 2;

            var result = water_PointDAL.Edit(water_Point);
            if (result.Code == (int)ResultCode.Success)
            {
                result.Msg = "校对处理成功";
            }
            return result;
        }

        /// <summary>
        /// 审核处理。
        /// </summary>
        /// <param name="water_Check"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-26 10:14:52。作者：王浩力
        public IResult Check(Water_check_history water_Check)
        {
            if (water_Check == null)
            {
                return new Result("无效参数");
            }
            if (water_Check.Check_stat == 0 && string.IsNullOrWhiteSpace(water_Check.Reject_reason))
            {
                return new Result("驳回理由不可为空");
            }
            water_Check.Check_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            water_Check.Check_user_id = CurrentLoginUser.Id;
            water_Check.Check_user_name = CurrentLoginUser.User_real_name;

            var result = water_PointDAL.Check(water_Check);
            return result;
        }

        /// <summary>
        /// 根据主表id，获取子项列表
        /// </summary>
        /// <param name="water_PointId"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-23 16:16:44。作者：王浩力
        public List<Water_point_item> GetWater_point_itemList(long water_PointId)
        {
            return water_Point_ItemDAL.GetList(water_PointId);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="where"></param>
        /// <param name="p"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-23 16:55:22    作者：王浩力
        public PageModel<Water_point> Page(Water_point where, int p, int rows)
        {
            if (CurrentLoginUser.Role_id == "校对人")
            {
                where.WorkList = new List<int>() { 1, 3 };
            }
            else if (CurrentLoginUser.Role_id == "审核人")
            {
                where.WorkList = new List<int>() { 2 };
            }

            //步骤值查询，//创建时间：2023-1-17 16:51:23。
            if (where.StepCurrent!=null )
            {
                where.WorkList = new List<int>() { (int)where.StepCurrent.ToMyInt64T2() };
            }

            return water_PointDAL.Page(where, p, rows);
        }

        /// <summary>
        /// 获取 下拉框选择的名称，子集
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-26 13:52:13。作者：王浩力
        public WaterPointView GetView(long id)
        {
            UserBusiness userBusiness = new UserBusiness();
            var userList = userBusiness.GetAllUser();

            var info = water_PointDAL.Get(id);
            var mp = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<Water_point, WaterPointView>();
            WaterPointView pointView = mp.Map(info);
            var dictAll = source_DictDAL.GetAll();

            //分析人姓名
            pointView.AnalyUserName = userList.Find(g => g.Id == pointView.Analyst)?.User_real_name; 

            pointView.AnalyUnit_Txt = dictAll.Find(g => g.Id == pointView.AnalyUnit)?.Item_name;

            //测试位置  //修改时间：2023-1-15 21:51:41。作者：王浩力
            //pointView.TestLocation_Txt = dictAll.Find(g => g.Id == pointView.TestLocation.ToMyInt64T2())?.Item_name;
            if (System.Text.RegularExpressions.Regex.IsMatch(pointView.TestLocation,"^\\d*$"))
            {
                pointView.TestLocation_Txt = dictAll.Find(g => g.Id == pointView.TestLocation.ToMyInt64T2())?.Item_name;
            }
            else
            {
                pointView.TestLocation_Txt = pointView.TestLocation;
            }

            pointView.Client_Txt = dictAll.Find(g => g.Id == pointView.Client)?.Item_name;
            pointView.water_Point_Items = water_Point_ItemDAL.GetList(id);

            //分析人，电子签名
            pointView.E6 = userList.FirstOrDefault(g => g.Id == info.Analyst.ToMyInt64T2())?.SignatureImgPath;

            //校对人，电子签名
            if (info.ProofreaderUserId.HasValue && info.ProofreaderUserId > 0)
            {
                pointView.E7 = userList.FirstOrDefault(g => g.Id == info.ProofreaderUserId)?.SignatureImgPath;
            }

            //审核人，电子签名
            //审核历史
            var history = water_Check_HistoryDAL.GetList(id);
            if (history?.Count > 0)
            {
                var find = history.OrderByDescending(g => g.Id).FirstOrDefault();
                if (find != null)
                {
                    var ckUser = userList.FirstOrDefault(g => g.Id == find.Check_user_id);
                    pointView.E5 = find?.Check_user_name;//审核人姓名
                    pointView.E8 = ckUser?.SignatureImgPath; //审核人电子签名图片url
                }
            }

            return pointView;
        }

        /// <summary>
        /// 获取处理日志
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-26 11:04:05；
        public List<Water_check_history> GetStepLog(long id)
        {
            var old = water_PointDAL.Get(id);
            List<Water_check_history> list = new List<Water_check_history>();

            //审核历史
            var history = water_Check_HistoryDAL.GetList(id);
            if (history?.Count > 0)
            {
                foreach (var item in history)
                {
                    if (item.Check_stat == 1)
                    {
                        item.Reject_reason = "审核通过";
                    }
                    else
                    {
                        item.Reject_reason = "驳回，" + item.Reject_reason;
                    }
                }
                list.AddRange(history);
            }
            if (!string.IsNullOrWhiteSpace(old.Proofreader))
            {
                Water_check_history water_Check_History = new Water_check_history();
                water_Check_History.Check_time = old.ProofreaderTime;
                water_Check_History.Check_user_name = old.Proofreader;
                water_Check_History.Reject_reason = "校对";
                list.Add(water_Check_History);
            }

            Water_check_history add = new Water_check_history();
            add.Check_time = old.Createtime;
            add.Check_user_name = old.InputUserRealName;
            add.Reject_reason = "录入";
            list.Add(add);
            return list.OrderBy(g => g.Check_time).ToList();
        }

        /// <summary>
        /// 水露点，统计数量，审核通过的，没有被删除的
        /// </summary>
        /// <returns></returns>
        /// 创建时间：2023-1-3 09:39:48。作者：王浩力
        public int GetCount()
        {
            return water_PointDAL.GetCount();
        }

        /// <summary>
        /// 导出excel
        /// </summary>
        /// <param name="water_Point">分页查询条件</param>
        /// <returns></returns>
        /// 创建时间：2023-1-4 09:31:09。作者：王浩力
        public IResult ExportExcel(Water_point where)
        {
            //列标题
            string[] cellTitleArr = new string[] {
            "报告编号","委托单位","分析人","流体介质温度","井站及井号","汽源","分析时间"
            ,"分析单位","测试位置","环境温度","创建时间","录入人姓名","校对人","校对时间"
            ,"审核人" ,"审核时间",
            "测试点压力","常压下测试露点","常压下含水量（g/m³）","测试压下露点","测试压下含水量（g/m³）"
            };

            int pageSize = 2000;//单个文件导出两千行记录
            string fileName = "water_" + Guid.NewGuid().ToString("N");

            //只查询审核通过的记录           
            try
            {
                var pageItem = water_Point_ItemDAL.GetPageItem(where, 1, 1);
                if (pageItem.Total == 0)
                {
                    return new ResultSuccess("没有记录");
                }

                //导出文件数
                int pageNum = (int)Math.Ceiling(pageItem.Total / (decimal)pageSize);

                for (int i = 1; i <= pageNum; i++)
                {
                    //注册编码提供程序
                    System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

                    Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook();
                    Aspose.Cells.Worksheet sheet = wb.Worksheets[0];
                    Aspose.Cells.Cells cells = sheet.Cells;
                    Aspose.Cells.Style style = wb.Styles[wb.Styles.Add()];
                    //style.Font.Name = "宋体";
                    style.Font.Size = 11;
                    style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
                    style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
                    style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
                    style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
                    style.Borders.SetColor(System.Drawing.Color.Black);
                    cells.ApplyStyle(style, new StyleFlag() { All = true });

                    //设置背景色。青色
                    Aspose.Cells.Style styleTitle = wb.Styles[wb.Styles.Add()];
                    styleTitle.ForegroundColor = System.Drawing.Color.Cyan;
                    styleTitle.Pattern = BackgroundType.Solid;
                    styleTitle.Font.IsBold = false;
                    styleTitle.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
                    styleTitle.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
                    styleTitle.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
                    styleTitle.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
                    styleTitle.Borders.SetColor(System.Drawing.Color.Black);

                    //从哪一行开始打印数据
                    int firstRow = 1;

                    //列中文标题
                    int total = 1;
                    if (cellTitleArr != null && cellTitleArr.Length > 0)
                    {
                        cells.ImportArray(cellTitleArr, 0, 0, false);//true竖直打印数据,false往右水平方向
                        //firstRow = firstRow + 1;
                        total++;
                    }
                    //标题样式，第1，2行标题 加粗
                    Aspose.Cells.Style styleTopTitle = wb.Styles[wb.Styles.Add()];
                    styleTopTitle.Font.IsBold = true;
                    Aspose.Cells.Range range = cells.CreateRange(0, 0, 1, cellTitleArr.Length);
                    range.ApplyStyle(styleTopTitle, new StyleFlag() { All = true });

                    //行背景色，相同主记录的背景色相同
                    Aspose.Cells.Style rowBg1 = wb.Styles[wb.Styles.Add()];
                    rowBg1.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
                    rowBg1.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
                    rowBg1.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
                    rowBg1.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;


                    Aspose.Cells.Style rowBg2 = wb.Styles[wb.Styles.Add()];
                    rowBg2.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
                    rowBg2.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
                    rowBg2.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
                    rowBg2.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
                    rowBg2.ForegroundColor = System.Drawing.Color.SpringGreen;
                    rowBg2.Pattern = BackgroundType.Solid;

                    //Aspose.Cells.Range range1 = cells.CreateRange(0, 0, 1, cells.Count);
                    //range1.ApplyStyle(rowBg2, new StyleFlag() { All = true });

                    WaterPointView waterPointView = null;

                    //当前文件数据
                    var page2 = water_Point_ItemDAL.GetPageItem(where, i, pageSize);
                    int lastColorMark = 1;
                    foreach (var item in page2.List)
                    {
                        //主表记录
                        if (item.WaterPointId != waterPointView?.Id)
                        {
                            waterPointView = GetView(item.WaterPointId);

                            if (lastColorMark == 1)
                            {
                                lastColorMark = 2;//颜色标记
                            }
                            else
                            {
                                lastColorMark = 1;//颜色标记
                            }
                        }
                        if (waterPointView == null)
                        {
                            continue;
                        }

                        List<object> rowCellArr = new List<object>() {
                            waterPointView.Report_no,
                            waterPointView.Client_Txt,
                            waterPointView.AnalyUserName,
                            waterPointView.FluTemperature,
                            waterPointView.WellAndWellNo,
                            waterPointView.AirSource,
                            waterPointView.Analytime,
                            waterPointView.AnalyUnit_Txt,//分析单位
                            waterPointView.TestLocation_Txt,
                            waterPointView.AmbientTemperature ,
                            waterPointView.Createtime ,
                            waterPointView.InputUserRealName,
                            waterPointView.Proofreader,
                            waterPointView.ProofreaderTime, //校对时间
                            waterPointView.E3,//审核人
                            waterPointView.E4, //审核时间

                            //----------- 子表记录 ----------------------
                            item.TestPressure,
                            item.OPTestTemp,
                            item.OPWater,
                            item.TestPoint,
                            item.TestWater,
                        };

                        //设置行背景色
                        Aspose.Cells.Range range3 = cells.CreateRange(firstRow, 0, 1, rowCellArr.Count);
                        if (lastColorMark == 1)
                        {
                            range3.ApplyStyle(rowBg1, new StyleFlag() { All = true });
                        }
                        else
                        {
                            range3.ApplyStyle(rowBg2, new StyleFlag() { All = true });
                        }

                        cells.ImportObjectArray(rowCellArr.ToArray(), firstRow, 0, false);

                        firstRow++;
                    }

                    //自适应宽
                    sheet.AutoFitColumns();

                    //自适应行高
                    sheet.AutoFitRows();

                    //文件保存路径
                    string filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "exoprt", fileName + "_" + i.ToString() + ".xlsx");
                    string fileFolderDeire = Path.GetDirectoryName(filePath);//目录信息
                    if (!System.IO.Directory.Exists(fileFolderDeire))
                    {
                        System.IO.Directory.CreateDirectory(fileFolderDeire);
                    }

                    //保存文件到本地
                    wb.Save(filePath, SaveFormat.Xlsx);
                }

                return new ResultSuccess($"导出成功，共{pageItem.Total}条数据，{pageNum}个文件") { Data = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "exoprt") };
            }
            catch (Exception ex)
            {
                return new Result("导出出错：" + ex.Message);
            }

        }

    }
}
